/*
 * @Author: Haochen
 * @Date: 2021-12-13 17:35:44
 * @LastEditTime: 2021-12-26 13:23:58
 * @FilePath: \recipes-admin-system\src\api\axios.js
 */
import axios from 'axios';
import { Message } from 'element-ui';
import router from '@/router';
// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    config.headers.Authorization = localStorage.token;
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (res) => {
    return res;
  },
  (err) => {
    if (err) {
      Message({
        type: 'error',
        message: '登录失效，请重新登录',
      });
      router.push('/login');
    }

    if (err && err.response && err.response.status) {
      switch (err.response.status) {
        case 401:
          Message({
            type: 'warning',
            message: '登录已过期，请重新登录',
          });
          router.push('/login');
          break;

        default:
          break;
      }
    }

    return Promise.reject(err);
  }
);
